package com.cmit.upay.monitor.config;

import com.cmit.upay.monitor.properties.ActiveMQProperties;
import com.cmit.upay.monitor.service.WriteDataService;
import com.cmit.upay.monitor.service.impl.WriteDataToCsvService;
import com.cmit.upay.monitor.service.impl.WriteDataToTxtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配置写服务
 */
@Configuration
public class WriteServiceConfig {
    @Autowired
    public ActiveMQProperties activeMQProperties;

    /**
     * 用于在写文件的时候，每个url对应一个目录，对应一个WriteDataService
     * @return
     */
    @Bean("writeServiceMap")
    public Map<String, WriteDataService> serviceMap() {
        Map<String, WriteDataService> map = new HashMap<>();
        List<String> urlList = null;
        WriteDataService service;
        // 判断使用Jmx监控还是jolokia监控
        if (activeMQProperties.getUseJmx()) {
            urlList = activeMQProperties.getJmxUrlList();
        } else {
            urlList = activeMQProperties.getAdminUrlList();
        }
        for (String url : urlList) {
            // 输出目录
            String outputDir = Paths.get(activeMQProperties.getOutputDir()).resolve(url.replaceAll(":", "_")).toAbsolutePath().toString();
            if ("csv".equalsIgnoreCase(activeMQProperties.getOutputFileType())) {
                service = new WriteDataToCsvService(outputDir, activeMQProperties.getPageSize());

            } else if ("txt".equalsIgnoreCase(activeMQProperties.getOutputFileType())) {
                service = new WriteDataToTxtService(outputDir, activeMQProperties.getPageSize());
            } else {
                throw new RuntimeException(String.format("你配置的文件类型为%s，不支持该文件类型", activeMQProperties.getOutputFileType()));
            }

            map.put(url, service);
        }
        return map;
    }
}
